﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.IO;

using TF.Access;
using log4net;
public partial class ImageUpload : System.Web.UI.Page
{
    private static readonly ILog log = LogManager.GetLogger(typeof(ImageUpload));
    private const string SCRIPT_TEMPLATE = "<" + "script " + "type=\"text/javascript\">window.parent.photoUploadComplete('{0}', {1},'{2}');" + "<" + "/script" + ">";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            //Sleeping for 10 seconds, fake delay, You should not it try at home.
            //System.Threading.Thread.Sleep(10 * 1000);
            UploadPhoto();
        }
    }

    #region CheckImagetype
    private System.Drawing.Imaging.ImageFormat GetImageType(object strContentType)
    {
        if ((strContentType.ToString().ToLower()) == "image/pjpeg")
        {
            return System.Drawing.Imaging.ImageFormat.Jpeg;
        }
        else if ((strContentType.ToString().ToLower()) == "image/gif")
        {
            return System.Drawing.Imaging.ImageFormat.Gif;
        }
        else if ((strContentType.ToString().ToLower()) == "image/bmp")
        {
            return System.Drawing.Imaging.ImageFormat.Bmp;
        }
        else if ((strContentType.ToString().ToLower()) == "image/tiff")
        {
            return System.Drawing.Imaging.ImageFormat.Tiff;
        }
        else if ((strContentType.ToString().ToLower()) == "image/x-icon")
        {
            return System.Drawing.Imaging.ImageFormat.Icon;
        }
        else if ((strContentType.ToString().ToLower()) == "image/x-png")
        {
            return System.Drawing.Imaging.ImageFormat.Png;
        }
        else if ((strContentType.ToString().ToLower()) == "image/x-emf")
        {
            return System.Drawing.Imaging.ImageFormat.Emf;
        }
        else if ((strContentType.ToString().ToLower()) == "image/x-exif")
        {
            return System.Drawing.Imaging.ImageFormat.Exif;
        }
        else if ((strContentType.ToString().ToLower()) == "image/x-wmf")
        {
            return System.Drawing.Imaging.ImageFormat.Wmf;
        }
        else
        {
            return System.Drawing.Imaging.ImageFormat.MemoryBmp;
        }
    }
    #endregion

    private void UploadPhoto()
    {
        string script = string.Empty;

        string uploadPath = string.Empty;
        string fileSrc = string.Empty;

        if ((filPhoto.PostedFile != null) && (filPhoto.PostedFile.ContentLength > 0))
        {
            if (!IsValidImageFile(filPhoto))
            {
                script = string.Format(SCRIPT_TEMPLATE, "上传文件不是有效的图片文件", "true");
            }
            else
            {
                TF_UserProfile userProfile = WebUtility.GetUserProfile();
                if (userProfile != null)
                {
                    try
                    {
                        string fileName = Path.GetFileName(filPhoto.PostedFile.FileName);

                        //绝对路径
                        uploadPath = Server.MapPath(ConfigurationManager.AppSettings["MediaURL"]) + Path.DirectorySeparatorChar + fileName;
                        //相对路径
                        fileSrc = ConfigurationManager.AppSettings["MediaURL"] + "/" + fileName;
                        filPhoto.PostedFile.SaveAs(uploadPath);
                        userProfile.Pic = fileSrc;
                        userProfile.Update();
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex.Message, ex);
                    }
                }
                else
                {
                    //
                }
            }
        }
        else
        {
            script = string.Format(SCRIPT_TEMPLATE, "请指定一个有效的文件", "true");
        }

        if (string.IsNullOrEmpty(script))
        {
            //Uploaded file is valid, now we can do whatever we like to do, copying it file system,
            //saving it in db etc.

            //Your Logic goes here

            script = string.Format(SCRIPT_TEMPLATE, "上传成功.", "false", fileSrc);
        }

        //Now inject the script which will fire when the page is refreshed.
        ClientScript.RegisterStartupScript(this.GetType(), "uploadNotify", script);
    }

    private static bool IsValidImageFile(HtmlInputFile file)
    {
        if (file.PostedFile.ContentType.ToString().ToLower().IndexOf("image") < 0)
        {
            return false;
        }

        bool ret = false;
        try
        {
            using (Bitmap bmp = new Bitmap(file.PostedFile.InputStream))
            {
                ret = true;
            }
        }
        catch (ArgumentException)
        {
            //throws exception if not valid image
            ret = false;
        }

        return ret;


    }
}
